<template>

  <template v-if="loading"><van-skeleton title :row="3" /></template>

  <template v-else>
    <DefaultCardHead :headinfo="headinfo"></DefaultCardHead>
    <van-cell-group inset class="L-margin-top-20">
      <div class="L-detail-title-row">
        <span class="L-text L-primary-text-color">
          <i class="iconfont icon-yuanzhu" style="color:#1683f7"></i>
          {{ currentActionName }}
        </span>
        <div>
          <van-uploader v-if="currentAction?.useai" :after-read="afterRead" style="margin-right:5px" :max-count="5"
            multiple>
            <span class="L-schedule-btn" v-if="isAiIdentify">Ai识别</span>
          </van-uploader>

          <span class="L-schedule-btn" @click="getCurrentActionData('new')" v-if="isCanAdd">添加一条</span>
          <span class="L-schedule-btn" @click="handleSkip" v-if="currentAction?.canskip"
            style="margin-left:5px">跳过</span>
        </div>
      </div>
      <div v-for="(item, index) in actionArr" :key="item.id" class="L-action-item">
        <div class="L-schedule-delete" v-if="actionArr.length > 1">
          <i class="iconfont icon-shanchu4 " style="color:#C0C4CC" @click="handleDelete(index)"></i>
        </div>

        <div v-for="(hitem, hindex) in item?.head" :key="hindex">
          <FormInput scene="action" v-for="(fitem, findex) in hitem.groupvalue" :key="findex" :formItem="fitem"
            @handleChange="handleChange" @handleClear="formHooks.handleClear" @getDistance="getDistance" ></FormInput>
        </div>
      </div>
    </van-cell-group>

    <div class="roundCir" v-if="currentAction.actionType === '签到'" @click="handleSubmit">签到</div>
    <div class="roundCir" v-else-if="currentAction.actionType === '签退'"  @click="handleSubmit">签退</div>
    <template v-else>
      <div class="L-bottom-space"></div>
      <div class="L-bottom-row">
        <van-button type="primary" block style="width: 90%;" @click="handleSubmit">提交</van-button>
      </div>
    </template>
  </template>

</template>

<script setup lang="ts">
import axios from "axios"
import qs from 'qs'

import { ref, onMounted, reactive } from "vue";
import { useRoute, useRouter } from "vue-router";
import { closeToast, showLoadingToast, showToast } from "vant";
const route = useRoute();
const router = useRouter();

// 引用表单hooks
import { useForm } from "@/hooks/formhooks.js";
const formHooks = useForm();


import { apiConfigurable } from "@/request/api/api";
import DefaultCardHead from "@/components/base/Card/DefaultCardHead.vue";
import FormInput from "@/components/base/Form/FormInput.vue";
import {currentTime} from "@/utils/func.js" 
onMounted(() => {
  getData();
});

const loading = ref(false);
const headinfo = ref({});
const currentActionId = ref(route.query.actionid || "");
const currentActionStates = ref("");
const currentActionName = ref("");
import type { actionVO } from "@/interface/interface"
const currentAction = ref<actionVO>({});
const currentActionIndex = ref(0);
const scenarioArr = ref([]);
const scenarioId = ref("");


function handleDelete(index: number) {
  actionArr.value.splice(index, 1)
}


// AI价签识别=====================================
const aiImageId = ref("")
const user = "abc-123"
const api_key = "app-Qiyj9P58BjM3edaB57ekf6qp"
interface uploadFileVO {
  file: File
}

// 读取上传文件
function afterRead(file: any) {
  const promiseArr = []
  const fileArr = []
  if (file.length) {
    for (let i = 0; i < file.length; i++) {
      promiseArr.push(handleUpload(file[i]))
    }
  } else {
    promiseArr.push(handleUpload(file))
  }
  Promise.all(promiseArr).then(res => {

    for (let i = 0; i < res.length; i++) {
      const item = res[i]
      if (item.status === 201) {
        const file = {
          "type": "image",
          "transfer_method": "local_file",
          "url": "",
          "upload_file_id": item.data.id
        }
        fileArr.push(file)
      }
    }
    if (fileArr.length > 0) {
      aiIdentify(fileArr)
    }
  })

}


//上传
function handleUpload(file: uploadFileVO) {

  const data = {
    user: user,
    file: file.file,
  };
  return axios.post("/ai/v1/files/upload", data,
    {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': `Bearer ${api_key}`
      }
    })
}


// ai识别
function aiIdentify(file: any) {


  const data = {
    inputs: { file },
    files: [],
    user: user,
  };

  showLoadingToast({
    message: "识别中...",
    forbidClick: true,
    duration: 0,
  });


  axios.post("/ai/v1/workflows/run", data, {
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${api_key}`,
    },
  }).then(res => {

    if (res.status === 200) {
      let outputs = JSON.parse(res.data.data.outputs.text)
      productClean(outputs)
    } else {

    }
  }).finally(() => {
    closeToast()
  });
}

const afterCleaningData = ref([])

//数据清洗
function productClean(oData) {
  showLoadingToast({
    message: "数据清洗中...",
    forbidClick: true,
    duration: 0,
  });
  axios.post("/api1/api/productqxnew", oData, {
    headers: {
      "Content-Type": "application/json",
    },
  }).then(res => {

    if (res.status === 200) {
      afterCleaningData.value = res.data
      autoFill()
    }

  }).finally(() => {
    closeToast()
  });
}

//自动填充
function autoFill() {
  const promiseArr = []
  const fieldmap = currentAction.value.fieldsMapping

  for (let i = 0; i < afterCleaningData.value.length; i++) {
    promiseArr.push(addActionData())
  }
  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });

  Promise.all(promiseArr).then(res => {
    for (let i = 0; i < res.length; i++) {
      const citem = afterCleaningData.value[i]
      const acitem = res[i].data.jsondata
      acitem['operate'] = 'new'
      for (let aci = 0; aci < acitem.head[0].groupvalue.length; aci++) {
        const fieldItem = acitem.head[0].groupvalue[aci]
        for (let mapi = 0; mapi < fieldmap.length; mapi++) {
          const mapItem = fieldmap[mapi]
          if (fieldItem.sField === mapItem.sfield) {
            if (citem.crm_product_code === '000000') {
              fieldItem.value = citem[mapItem.model]
              if (mapItem.model === "crm_productname") {
                fieldItem.valuehidden = citem.crm_productid
              }
              fieldItem.errorMessage = ""
            } else {
              fieldItem.errorMessage = getAiErrorMessage(mapItem.model, citem)
            }
          }
        }
      }

      let hasHandle = false
      for (let k = 0; k < actionArr.value.length; k++) {
        let actionItem = actionArr.value[k]
        if (checkActionItemIsEmptyData(actionItem)) {
          actionArr.value[k] = acitem
          hasHandle = true
          break;
        } else {
          continue
        }
      }
      if (!hasHandle) {
        actionArr.value.unshift({ id: new Date().getTime(), ...acitem })
      }
    }

  }).finally(() => {
    closeToast()
  });

}

function getAiErrorMessage(modelString: string, citem): string {
  let res = ""

  switch (modelString) {
    case "crm_productname":
      res = `未匹配到产品 ${citem.productname}`
      break;
    case "crm_sspec":
      res = `未匹配到规格 ${citem.sspec}`
      break;
    case "crm_measurement":
      res = `未匹配到计量单位 ${citem.measurement}`
      break;
  }
  return res
}

function addActionData() {

  // 请求scenario.getaction.do的目的不是为了获取字段结构,而是为了获取id(例如:xlsb_id)否则插提交时会报错
  const { idobject, itemid } = route.query;
  const url = "scenario.getaction.do";
  const { toBo: sobject, fields, toId, zdys } = currentAction.value;
  const data = {
    sobject,
    fields: JSON.stringify(fields),
    headid: itemid,
    headobject: idobject,
    zdys: JSON.stringify(zdys) 
  };
  return apiConfigurable(url, data)
}

function checkActionItemIsEmptyData(actionItem) {
  const fileArr = actionItem.head[0].groupvalue
  return fileArr.every(item => !item.value && !item.errorMessage)
}



// =========================================================


function getData() {
  const { idobject, itemid } = route.query;
  const url = idobject + ".check.do";
  const data = {
    [idobject + "_id"]: itemid,
  };
  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });
  loading.value = true;

  apiConfigurable(url, data).then((res) => {
    if (res.code === 0) {
      const { jsondata } = res.data;
      headinfo.value = jsondata.headinfo;
      scenarioArr.value = jsondata.scenario.scenarioInfo;
      scenarioId.value = jsondata.scenario.scenarioId;

      currentAction.value = jsondata.scenario.scenarioInfo.find((item, index) =>
        getCurrentAction(item, index)
      );

      // if (
      //   currentAction.value.actionType === "签到" ||
      //   currentAction.value.actionType === "签退"
      // ) {
      //   getlocation();
      // }
      closeToast();
      let operate = currentAction.value.toPage || "new";

      getCurrentActionData(operate);

    }
  });
}

function getCurrentAction(item, index) {
  if (currentActionId.value) {
    if (item.actionId === currentActionId.value) {
      currentActionIndex.value = index;
      currentActionStates.value = item.states;
      currentActionName.value = item.actionName;
    }
    return item.actionId === currentActionId.value;
  } else {
    if (item.ended === false) {
      currentActionIndex.value = index;
      currentActionStates.value = item.states;
      currentActionName.value = item.actionName;
    }
    return item.ended === false;
  }
}

// 字段值发生变化
function handleChange(item, value, valuehidden = "") {
  item.value = value;
  // if (valuehidden) {
    item.valuehidden = valuehidden || '';
  // }
}

const actionArr = ref([]);
const isCanAdd = ref(false);
const isAiIdentify = ref(true)



function getCurrentActionData(operate: string) {
  const { idobject, itemid } = route.query;
  const url = "scenario.getaction.do";
  const { toBo: sobject, fields, toId, zdys } = currentAction.value;

  if (operate === "edit") {
    const toIdArr = JSON.parse(toId);
    const promiseArr = [];
    for (let i = 0; i < toIdArr.length; i++) {
      const data = {
        sobject,
        [sobject + "_id"]: toIdArr[i],
        fields: JSON.stringify(fields),
        headid: itemid,
        headobject: idobject,
        zdys: JSON.stringify(zdys) 
      };
      promiseArr.push(apiConfigurable(url, data));
    }

    showLoadingToast({
      message: "加载中...",
      forbidClick: true,
      duration: 0,
    });
    Promise.all(promiseArr).then((res) => {
      if (res.every((item) => item.code === 0)) {
        res.forEach((item) => {
          item.data.jsondata["operate"] = operate;
          actionArr.value.push({ id: new Date().getTime(), ...item.data.jsondata });
        });

        isCanAdd.value = res[0].data.jsondata.newline;

        closeToast();
      }
    })
      .finally(() => {
        loading.value = false;
      });
  } else if (operate === "new") {
   
    const data = {
      sobject,
      fields: JSON.stringify(fields),
      headid: itemid,
      headobject: idobject,
      zdys: JSON.stringify(zdys)
    };
    showLoadingToast({
      message: "加载中...",
      forbidClick: true,
      duration: 0,
    });
    apiConfigurable(url, data).then((res) => {
      if (res.code === 0) {
        res.data.jsondata["operate"] = operate;
        actionArr.value.push({ id: new Date().getTime(), ...res.data.jsondata });
        isCanAdd.value = res.data.jsondata.newline;
        closeToast();
      }
    }).finally(() => {
      loading.value = false;
      // document.body.scrollTo({top:document.body.scrollHeight,behavior: 'smooth' });
      window.scrollTo(0, document.body.scrollHeight);
    });
  }
}




interface submitParams {
  [key: string]: any;
}
//提交
function handleSubmit() {
  const url = "scenario.getaction.do";
  const { toBo: idobject } = currentAction.value;
  const submitData = actionArr.value;
  const promiseArr = [];

  for (let i = 0; i < submitData.length; i++) {
    const data: submitParams = {};
    data[idobject + "_id"] = submitData[i][idobject + "_id"];
    for (let groupindex in submitData[i].head) {
      let itemgroup = submitData[i].head[groupindex].groupvalue;
      for (let itemindex in itemgroup) {
        let itemdata = itemgroup[itemindex];
        // 签到时间 & 签到时间
        if(itemdata.sField === 'dbegin' || itemdata.sField === 'dend'){
          itemdata.value = currentTime()
        }

       

        
        if (itemdata.sUIType === "ref") {
          data[itemdata.idObject + "_" + itemdata.sField] = itemdata.valuehidden;
          data[itemdata.idObject + "_" + itemdata.sField + "_ref"] = itemdata.value;
        } else if (itemdata.sUIType === "enum") {
          data[itemdata.idObject + "_" + itemdata.sField] = itemdata.valuehidden;
          data[itemdata.idObject + "_" + itemdata.sField + "_enum"] = itemdata.value;
        } else if (itemdata.sUIType === "file" || itemdata.sUIType === "picture"
        ) {
          data[itemdata.idObject + "_" + itemdata.sField] = itemdata.valuehidden;
          data[itemdata.idObject + "_" + itemdata.sField + "_title"] = itemdata.value;
        } else {
          data[itemdata.idObject + "_" + itemdata.sField] = itemdata.value;
        }
      }
    }

    

    const url = `${idobject}.${submitData[i].operate}save.do`;

    promiseArr.push(apiConfigurable(url, data));
  }

  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });

  Promise.all(promiseArr).then((res) => {
    if (res.every((item) => item.code === 0)) {
      handleSave("end");
      closeToast();
    }
  });
}

//跳过
function handleSkip() {
  handleSave("skip");
}

async function handleSave(states = "end") {
  const { idobject, itemid } = route.query;
  const { actionId: idaction, toBo } = currentAction.value;
  const toiddata = actionArr.value.map((item) => {
    return item[`${toBo}_id`];
  });

  let data = {
    idscenario: scenarioId.value, //场景ID
    idaction, //动作ID
    toobject: toBo, //动作对象
    toiddata: JSON.stringify(toiddata), //动作对象id数组
    sobject: idobject,
    iddata: itemid,
    states: states,
    ended: false,
  };
  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });

  const saveLogRes = await savelog(data);

  closeToast()
  if (saveLogRes.code === 0) {
    if (scenarioArr.value.length > currentActionIndex.value + 1) {
      data["ended"] = false;
    } else {
      data["ended"] = true;
    }
    scenarioEnd(data);
  }
}

function savelog(data) {
  const url = "scenario.savelog.do";
  return apiConfigurable(url, data);
}

function scenarioEnd(data) {
  const url = "scenario.end.do";
  apiConfigurable(url, data).then((res) => {
    if (res.code === 0) {
      // 路由当中有actionId代表编辑已经操作过的步骤,操作结束后要返回上一页
      if (currentActionId.value) {
        router.go(-1);
        return;
      }

      //data.ended代表当前场景是否完成,true代表已完成(返回上一页),false代表未完成(进入下一个动作)
      if (!data.ended) {
        const { idobject, itemid, stitle } = route.query;
        const query = { idobject, itemid, stitle };
        actionArr.value = [];
        getData();
      } else {
        router.go(-1);
      }
    }
  });
}

function getDistance(center) {
  const { idobject: bo, itemid: id } = route.query


  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });
  const url = "scenario.getdistance.do"
  const data = qs.stringify({
    center: JSON.stringify(center.value),
    bo,
    id
  })

  apiConfigurable(url, data).then(res => {
    if (res.code === 0) {
      const { distance } = res.data

      for (let i = 0; i < actionArr.value.length; i++) {
          const acitonItem = actionArr.value[i]
          for(let j=0;j<acitonItem.head.length;j++){
            const filesArr = acitonItem.head[j].groupvalue
            for(let k=0;k<filesArr.length;k++){
              const item = filesArr[k]
              if(item.sField==="distance"){
                item.value = distance
              }
            }
          }
      }


    }
  }).finally(() => {
    closeToast()
  })
}




</script>

<style scoped>
.L-action-item {
  position: relative;
  border-bottom: 10px solid #F0F2F5;

}

.L-schedule-delete {
  /* position: absolute; */
  right: 0px;
  top: 0px;
  z-index: 10;
  padding: 0px 10px;
  text-align: right;
}

.roundCir {
  width: 134px;
  height: 134px;
  background: linear-gradient(180deg, #fdc75b 0%, #ff9d02 100%);
  filter: drop-shadow(0 0 9px #ffc523cc);
  border-radius: 50%;
  border: none;
  color: #fff;
  margin: 30px auto;
  font-size: 20px;

  display: flex;
  justify-content: center;
  align-items: center;
}
</style>